package com.test.api.controller;
import Entity.Student;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import com.test.api.util.*;
@CrossOrigin
@RestController
@RequestMapping("/student")
public class StudentController {

    private List<Student> arrlist=StudentData.initData();
    @RequestMapping("/getStudent")
    JSONObject getStudents()
    {
        JSONObject retobject=new JSONObject();
        retobject.put("data",arrlist);
        retobject.put("code","20000");
        return retobject;
    }
    @RequestMapping("/deleteStudent")
    JSONObject deleteStudent(@RequestBody JSONObject reqMap){
        String no=(String)reqMap.get("no");
        boolean deleteflag=false;
        for(int i=arrlist.size()-1;i>=0;i--)
        {
            if(arrlist.get(i).getNo().equals(no))
            {
                arrlist.remove(i);
                deleteflag=true;
            }
        }
        JSONObject retobject=new JSONObject();
        if(deleteflag)
        retobject.put("msg","删除学生成功");
        else
            retobject.put("msg","查无此学生");
        retobject.put("code","20000");
        return  retobject;
    }

    @RequestMapping("/searchStudentByno")
    JSONObject searchStudentByno(@RequestBody JSONObject reqMap)
    {
        String no=(String)reqMap.get("no");
        List<Student> result=new ArrayList<Student>();
        for(int i=arrlist.size()-1;i>=0;i--)
        {
            if(arrlist.get(i).getNo().equals(no))
            {
               Student student=new Student(arrlist.get(i).getName(),arrlist.get(i).getNo(),arrlist.get(i).getAge());
               result.add(student);
            }
        }
        JSONObject retobject=new JSONObject();
        retobject.put("data",result);
        retobject.put("code","20000");
        return retobject;

    }

        @RequestMapping("/addStudent")
    JSONObject addStudent(@RequestBody JSONObject reqMap) {

        String name=(String)reqMap.get("name");
        String no=(String)reqMap.get("no");
        int age;
        try {
             age = Integer.valueOf((String) reqMap.get("age"));
        }
        catch (Exception ex)
        {
            JSONObject retobject=new JSONObject();
            retobject.put("msg","添加失败,原因是年龄不是整数");
            retobject.put("code","20001");
            return retobject;
        }
        Student student=new Student(name,no,age);
        arrlist.add(student);
        JSONObject retobject=new JSONObject();
        retobject.put("msg","添加学生成功");
        retobject.put("code","20000");
        return  retobject;


    }

}
